package com.atguigu.yygh.orders.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.atguigu.yygh.enums.PaymentTypeEnum;
import com.atguigu.yygh.enums.RefundStatusEnum;
import com.atguigu.yygh.handler.YyghException;
import com.atguigu.yygh.model.order.OrderInfo;
import com.atguigu.yygh.model.order.PaymentInfo;
import com.atguigu.yygh.model.order.RefundInfo;
import com.atguigu.yygh.orders.service.OrderService;
import com.atguigu.yygh.orders.service.PaymentInfoService;
import com.atguigu.yygh.orders.service.RefundInfoService;
import com.atguigu.yygh.orders.service.WeixinService;
import com.atguigu.yygh.orders.utils.ConstantPropertiesUtils;
import com.atguigu.yygh.orders.utils.HttpClient;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.wxpay.sdk.WXPayConstants;
import com.github.wxpay.sdk.WXPayUtil;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class WeixinServiceImpl implements WeixinService {


    @Autowired
    private OrderService orderService;

    @Autowired
    private PaymentInfoService paymentInfoService;


    @Autowired
    private RefundInfoService refundInfoService;

    //生成二维码
    @Override
    public Map createNative(Long orderId) {
        try {
            OrderInfo orderInfo = orderService.getOrderInfo(orderId);
            //添加支付记录
            paymentInfoService.savePaymentInfo(orderInfo, PaymentTypeEnum.WEIXIN.getStatus());

            //封装数据
            //1、设置参数
            Map paramMap = new HashMap();
            paramMap.put("appid", ConstantPropertiesUtils.APPID);//公众号id
            paramMap.put("mch_id", ConstantPropertiesUtils.PARTNER);//商户号
            paramMap.put("nonce_str", WXPayUtil.generateNonceStr());//随机值

            Date reserveDate = orderInfo.getReserveDate();
            String reserveDateString = new DateTime(reserveDate).toString("yyyy/MM/dd");
            String body = reserveDateString + "就诊"+ orderInfo.getDepname();
            paramMap.put("body", body);//扫码后显示内容

            paramMap.put("out_trade_no", orderInfo.getOutTradeNo());//交易号
            //paramMap.put("total_fee", order.getAmount().multiply(new BigDecimal("100")).longValue()+"");
            paramMap.put("total_fee", "1");//为了测试

            paramMap.put("spbill_create_ip", "127.0.0.1");//客户端ip地址
            paramMap.put("notify_url", "http://guli.shop/api/order/weixinPay/weixinNotify");
            paramMap.put("trade_type", "NATIVE");//支付二维码类型


            //httpclient请求
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
            //设置参数 xml格式  商户key加密
            client.setXmlParam(WXPayUtil.generateSignedXml(paramMap, ConstantPropertiesUtils.PARTNERKEY));
            //设置支持https
            client.setHttps(true);
            //发送请求
            client.post();
            //获取返回数据
            String content = client.getContent();
            System.out.println("生成二维码返回值 content = " + content);
            Map<String, String> resultMap = WXPayUtil.xmlToMap(content);

            Map map = new HashMap<>();
            map.put("orderId", orderId);
            map.put("totalFee", orderInfo.getAmount());
            map.put("resultCode", resultMap.get("result_code"));//状态码
            map.put("codeUrl", resultMap.get("code_url"));//微信返回二维码地址
            return map;


        } catch (Exception e) {
            e.printStackTrace();
        }


        return null;
    }


    //根据订单号去微信第三方查询支付状态
    @Override
    public Map queryPayStatus(Long orderId, String paymentType) {
        try {
            OrderInfo orderInfo = orderService.getById(orderId);

            //1、封装参数
            Map paramMap = new HashMap<>();
            paramMap.put("appid", ConstantPropertiesUtils.APPID);
            paramMap.put("mch_id", ConstantPropertiesUtils.PARTNER);
            paramMap.put("out_trade_no", orderInfo.getOutTradeNo());
            paramMap.put("nonce_str", WXPayUtil.generateNonceStr());//随机字符串

            //发送
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/orderquery");
            client.setXmlParam(WXPayUtil.generateSignedXml(paramMap, ConstantPropertiesUtils.PARTNERKEY));
            client.setHttps(true);
            client.post();

            //微信返回数据
            String xml = client.getContent();
            System.out.println("支付状态返回 xml = " + xml);

            Map<String, String> map = WXPayUtil.xmlToMap(xml);
            return map;
        } catch (Exception e) {
            e.printStackTrace();
            throw new YyghException(20001,"支付失败");
        }

    }


    //退款
    @Override
    public Boolean refund(Long orderId) {

        //根据订单号查询支付记录
        PaymentInfo paymentInfo =
                paymentInfoService.getOne(new QueryWrapper<PaymentInfo>()
                .eq("order_id", orderId));

        //添加退款记录
        RefundInfo refundInfo = refundInfoService.saveRefundInfo(paymentInfo);
        if(refundInfo.getRefundStatus().intValue() == RefundStatusEnum.REFUND.getStatus().intValue()) {
            return true;
        }

        //获取流水号和微信返回
        Map<String,String> paramMap = new HashMap<>(8);
        paramMap.put("appid",ConstantPropertiesUtils.APPID);       //公众账号ID
        paramMap.put("mch_id",ConstantPropertiesUtils.PARTNER);   //商户编号
        paramMap.put("nonce_str",WXPayUtil.generateNonceStr());
        paramMap.put("transaction_id",paymentInfo.getTradeNo()); //微信订单号
        paramMap.put("out_trade_no",paymentInfo.getOutTradeNo()); //商户订单编号
        paramMap.put("out_refund_no","tk"+paymentInfo.getOutTradeNo()); //商户退款单号
        //       paramMap.put("total_fee",paymentInfoQuery.getTotalAmount().multiply(new BigDecimal("100")).longValue()+"");
        //       paramMap.put("refund_fee",paymentInfoQuery.getTotalAmount().multiply(new BigDecimal("100")).longValue()+"");
        paramMap.put("total_fee","1");
        paramMap.put("refund_fee","1");

        //发送退款请求
        HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/secapi/pay/refund");
        try {
            client.setHttps(true);
            client.setXmlParam(WXPayUtil.generateSignedXml(paramMap, ConstantPropertiesUtils.PARTNERKEY));
            client.setCert(true);
            client.setCertPassword(ConstantPropertiesUtils.PARTNER);
            client.post();
            String xml = client.getContent();
            Map<String, String> map = WXPayUtil.xmlToMap(xml);
            if (null != map && WXPayConstants.SUCCESS.equalsIgnoreCase(map.get("result_code"))) {
                //更新退款状态
                refundInfo.setCallbackTime(new Date());
                refundInfo.setTradeNo(map.get("refund_id"));
                refundInfo.setRefundStatus(RefundStatusEnum.REFUND.getStatus());
                refundInfo.setCallbackContent(JSONObject.toJSONString(map));
                refundInfoService.updateById(refundInfo);
                return true;
            }


        } catch (Exception e) {
            e.printStackTrace();
        }


        return false;
    }


}
